<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        #canvas {
            border: 1px solid red;
            display: block;
            margin: 0 auto;
        }
    </style>
</head>

<body>
    <canvas id="canvas" width="500px" height="500px"></canvas>
    <script>
        //开启canvas代码提示
        /** @type {HTMLCanvasElement} */
        // 1.获取画布
        let canvas = document.getElementById('canvas')
        // 2.获取画布的上下文
        let ctx = canvas.getContext('2d')
        // 画布的宽高
        let w = 500
        let h = 500
        // 求的圆点 半径
        let x = 100
        let y = 100
        let r = 20
        // 水平速度
        xSpeed = 10
        ySpeed = 6

        setInterval(() => {
            // 动画中要用到清除画布,否则不画圆
            ctx.beginPath()//重置路径
            ctx.clearRect(0, 0, w, h)

            // 在小球碰到边缘时，速度取相反即可!!!
            if (x - r <= 0 || x + r >= w) {
                xSpeed = -xSpeed
            }
            // 水平运动
            x = x + xSpeed

            if (y - r <= 0 || y + r >= h) {
                ySpeed = -ySpeed
            }
            // 垂直运动
            y += ySpeed

            drawCircle(x, y, r)
        }, 50)

        /**
         * @description: 画小球
         * @param {*} x
         * @param {*} y
         * @param {*} r
         * @return {*}
         */
        function drawCircle(x, y, r) {
            ctx.arc(x, y, r, 0, Math.PI * 2)
            ctx.fillStyle = 'gold'
            ctx.fill()
        }
    </script>
</body>

</html>